package com.atguigu.realtime.app.dwd;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONAware;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.realtime.app.BaseAppV1;
import com.atguigu.realtime.commont.Constant;
import com.atguigu.realtime.util.AtguiguUtil;
import com.atguigu.realtime.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/11/23 8:55
 */
public class DwdLogApp extends BaseAppV1 {
    private static final String START = "start";
    private static final String PAGE = "page";
    private static final String DISPLAY = "display";
    
    public static void main(String[] args) {
        new DwdLogApp().init(2001, 1, "DwdLogApp", "DwdLogApp", Constant.TOPIC_ODS_LOG);
    }
    
    @Override
    protected void run(StreamExecutionEnvironment env,
                       DataStreamSource<String> stream) {
        // 对数据流进行业务处理
        // 1. 对新老用户字段进行纠正
        SingleOutputStreamOperator<JSONObject> validatedStream = distinguishNewOrOld(stream);
        // 2. 对数据进行分流: 启动  曝光 页面
        HashMap<String, DataStream<JSONObject>> threeStreams = splitStream(validatedStream);
        
        // 3. 不同的流写入到不同的topic中
        writeToKafka(threeStreams);
        
    }
    
    private void writeToKafka(HashMap<String, DataStream<JSONObject>> streams) {
        streams
            .get(START)
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_START));
        
        streams
            .get(DISPLAY)
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_DISPLAY));
        streams
            .get(PAGE)
            .map(JSONAware::toJSONString)
            .addSink(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_PAGE));
        
    }
    
    private HashMap<String, DataStream<JSONObject>> splitStream(SingleOutputStreamOperator<JSONObject> validatedStream) {
        OutputTag<JSONObject> pageTag = new OutputTag<JSONObject>(PAGE) {};
        OutputTag<JSONObject> displayTag = new OutputTag<JSONObject>(DISPLAY) {};
        
        // 对日志进行分流处
        // 主流: 启动日记  测输出: 页面和曝光
        SingleOutputStreamOperator<JSONObject> startStream = validatedStream
            .process(new ProcessFunction<JSONObject, JSONObject>() {
                @Override
                public void processElement(JSONObject obj,
                                           Context ctx,
                                           Collector<JSONObject> out) throws Exception {
                    if (obj.containsKey("start")) {
                        out.collect(obj);
                    } else {
                        // 其他日志分别判断曝光和日志
                        
                        if (obj.containsKey("page")) {
                            ctx.output(pageTag, obj);
                        }
                        
                        if (obj.containsKey("displays")) {
                            JSONArray displays = obj.getJSONArray("displays");
                            
                            for (int i = 0; i < displays.size(); i++) {
                                JSONObject display = displays.getJSONObject(i);
                                display.putAll(obj.getJSONObject("common"));
                                display.putAll(obj.getJSONObject("page"));
                                display.put("ts", obj.getLong("ts"));
                                
                                ctx.output(displayTag, display);
                            }
                        }
                        
                    }
                    
                }
            });
        DataStream<JSONObject> pageStream = startStream.getSideOutput(pageTag);
        DataStream<JSONObject> displayStream = startStream.getSideOutput(displayTag);
        
        HashMap<String, DataStream<JSONObject>> streams = new HashMap<>();
        streams.put(START, startStream);
        streams.put(PAGE, pageStream);
        streams.put(DISPLAY, displayStream);
        return streams;
        
    }
    
    // 区别新老客户
    private SingleOutputStreamOperator<JSONObject> distinguishNewOrOld(DataStreamSource<String> stream) {
        /*
        针对某个mid, 他的第一条记录应该是 1, 其他的都应用是 0
        
        考虑到数据的乱序:
        1. 使用事件时间
        2. 使用窗口
            每个mid的第一个窗口中时间戳最小的那个数据的is_new 是1, 其他都是 0
            其他的所有窗口都是 0
         */
        return stream
            .map(JSON::parseObject)
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((log, ts) -> log.getLong("ts"))
            )
            .keyBy(log -> log.getJSONObject("common").getString("mid"))
            .window(TumblingEventTimeWindows.of(Time.seconds(5)))
            .process(new ProcessWindowFunction<JSONObject, JSONObject, String, TimeWindow>() {
                
                private ValueState<Boolean> isFirstWindowState;
                
                @Override
                public void open(Configuration parameters) throws Exception {
                    isFirstWindowState = getRuntimeContext()
                        .getState(new ValueStateDescriptor<Boolean>("isFirstWindowState", Boolean.class));
                }
                
                @Override
                public void process(String key,
                                    Context ctx,
                                    Iterable<JSONObject> elements,
                                    Collector<JSONObject> out) throws Exception {
                    if (isFirstWindowState.value() == null) {
                        isFirstWindowState.update(true);
                        
                        List<JSONObject> list = AtguiguUtil.toList(elements);
                        //                        list.sort((o1, o2) -> o1.getLong("ts").compareTo(o2.getLong("ts")));
                        list.sort(Comparator.comparing(o -> o.getLong("ts")));
                        
                        for (int i = 0; i < list.size(); i++) {
                            JSONObject obj = list.get(i);
                            if (i == 0) {
                                obj.getJSONObject("common").put("is_new", "1");
                            } else {
                                obj.getJSONObject("common").put("is_new", "0");
                                
                            }
                            out.collect(obj);
                        }
                        
                    } else {
                        // 不是第一个窗口, 所有的is_new都是0
                        for (JSONObject obj : elements) {
                            
                            obj.getJSONObject("common").put("is_new", "0");
                            
                            out.collect(obj);
                        }
                    }
                }
            });
        
    }
}
